package com.moujitx.wecom.common;

import com.moujitx.wecom.entity.MessageLog;
import com.moujitx.wecom.repository.MessageLogRepository;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.experimental.UtilityClass;

/**
 * 企业微信API工具类
 */
@UtilityClass
public class Wecom {
    private static MessageLogRepository messageLogRepository;

    public static void setMessageLogRepository(MessageLogRepository repository) {
        messageLogRepository = repository;
    }

    private static void logMessage(MessageLog messageLog) {
        if (messageLogRepository != null) {
            messageLogRepository.save(messageLog);
        }
    }

    /**
     * 获取访问令牌
     * 
     * @param corpId 企业ID
     * @param secret 应用密钥
     * @return 访问令牌，如果获取失败则返回null
     */
    public static String getAccessToken(String corpId, String secret) {
        String tokenUrl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + corpId
                + "&corpsecret=" + secret;
        String result = HttpUtil.get(tokenUrl);
        JSONObject jsonObject = JSONUtil.parseObj(result);
        if (jsonObject.getInt("errcode") == 0) {
            return jsonObject.getStr("access_token");
        } else {
            return null;
        }
    }

    /**
     * 发送Markdown消息
     * 
     * @param accessToken 访问令牌
     * @param toUser 接收人，多个接收人用|分隔，@all表示所有人
     * @param content 消息内容
     * @param agentId 应用ID
     * @return 发送结果
     */
    public static String sendMarkdownMessage(String accessToken, String toUser, String content, Integer agentId, Long wecomConfigId) {
        MessageLog log = new MessageLog();
        log.setMessageType("MARKDOWN");
        log.setContent(content);
        log.setStatus("PENDING");
        log.setDestinationId(wecomConfigId);
        
        String url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + accessToken;

        JSONObject markdown = new JSONObject();
        markdown.set("content", content);

        JSONObject json = new JSONObject();
        json.set("touser", toUser);
        json.set("msgtype", "markdown");
        json.set("agentid", agentId);
        json.set("markdown", markdown);

        String body = json.toString();
        String result = HttpUtil.post(url, body);
        
        JSONObject jsonResult = JSONUtil.parseObj(result);
        if (jsonResult.getInt("errcode") == 0) {
            log.setStatus("SUCCESS");
        } else {
            log.setStatus("FAILED");
            log.setErrorMessage(jsonResult.getStr("errmsg"));
        }
        log.setToUser(toUser);
        logMessage(log);
        
        return result;
    }
    
    /**
     * 发送文本消息
     * 
     * @param accessToken 访问令牌
     * @param toUser 接收人，多个接收人用|分隔，@all表示所有人
     * @param content 消息内容
     * @param agentId 应用ID
     * @return 发送结果
     */
    public static String sendTextMessage(String accessToken, String toUser, String content, Integer agentId, Long wecomConfigId) {
        MessageLog log = new MessageLog();
        log.setMessageType("TEXT");
        log.setContent(content);
        log.setStatus("PENDING");
        log.setDestinationId(wecomConfigId);
        
        String url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + accessToken;

        JSONObject text = new JSONObject();
        text.set("content", content);

        JSONObject json = new JSONObject();
        json.set("touser", toUser);
        json.set("msgtype", "text");
        json.set("agentid", agentId);
        json.set("text", text);

        String body = json.toString();
        String result = HttpUtil.post(url, body);
        
        JSONObject jsonResult = JSONUtil.parseObj(result);
        if (jsonResult.getInt("errcode") == 0) {
            log.setStatus("SUCCESS");
        } else {
            log.setStatus("FAILED");
            log.setErrorMessage(jsonResult.getStr("errmsg"));
        }
        log.setToUser(toUser);
        logMessage(log);
        
        return result;
    }
    
    /**
     * 发送图文消息
     * 
     * @param accessToken 访问令牌
     * @param toUser 接收人，多个接收人用|分隔，@all表示所有人
     * @param title 标题
     * @param description 描述
     * @param url 跳转链接
     * @param picUrl 图片链接
     * @param agentId 应用ID
     * @return 发送结果
     */
    public static String sendNewsMessage(String accessToken, String toUser, String title, 
            String description, String url, String picUrl, Integer agentId, Long wecomConfigId) {
        MessageLog log = new MessageLog();
        log.setMessageType("NEWS");
        log.setTitle(title);
        log.setContent(description);
        log.setUrl(url);
        log.setPicUrl(picUrl);
        log.setStatus("PENDING");
        log.setDestinationId(wecomConfigId);
        
        String apiUrl = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + accessToken;

        JSONObject article = new JSONObject();
        article.set("title", title);
        article.set("description", description);
        article.set("url", url);
        article.set("picurl", picUrl);

        JSONArray articles = new JSONArray();
        articles.add(article);

        JSONObject news = new JSONObject();
        news.set("articles", articles);

        JSONObject json = new JSONObject();
        json.set("touser", toUser);
        json.set("msgtype", "news");
        json.set("agentid", agentId);
        json.set("news", news);

        String body = json.toString();
        String result = HttpUtil.post(apiUrl, body);
        
        JSONObject jsonResult = JSONUtil.parseObj(result);
        if (jsonResult.getInt("errcode") == 0) {
            log.setStatus("SUCCESS");
        } else {
            log.setStatus("FAILED");
            log.setErrorMessage(jsonResult.getStr("errmsg"));
        }
        log.setToUser(toUser);
        logMessage(log);
        
        return result;
    }
    
    /**
     * 发送模板卡片消息
     * 
     * @param accessToken 访问令牌
     * @param toUser 接收人，多个接收人用|分隔，@all表示所有人
     * @param title 标题
     * @param description 描述
     * @param url 跳转链接
     * @param agentId 应用ID
     * @return 发送结果
     */
    public static JSONObject sendTemplateCardMessage(String accessToken, String toUser, String title, 
            String description, String url, Integer agentId, Long wecomConfigId) {
        MessageLog log = new MessageLog();
        log.setMessageType("TEMPLATE_CARD");
        log.setTitle(title);
        log.setContent(description);
        log.setUrl(url);
        log.setStatus("PENDING");
        log.setDestinationId(wecomConfigId);
        
        String apiUrl = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + accessToken;

        JSONObject mainTitle = new JSONObject();
        mainTitle.set("title", title);
        
        JSONObject source = new JSONObject();
        source.set("desc", "消息来源");

        JSONObject cardAction = new JSONObject();
        cardAction.set("type", 1);
        cardAction.set("url", url);

        JSONObject templateCard = new JSONObject();
        templateCard.set("card_type", "text_notice");
        templateCard.set("source", source);
        templateCard.set("main_title", mainTitle);
        templateCard.set("task_id", System.currentTimeMillis() + "");
        templateCard.set("emphasis_content", new JSONObject().set("title", "重要"));
        templateCard.set("sub_title_text", description);
        templateCard.set("card_action", cardAction);

        JSONObject json = new JSONObject();
        json.set("touser", toUser);
        json.set("msgtype", "template_card");
        json.set("agentid", agentId);
        json.set("template_card", templateCard);

        String body = json.toString();
        String result = HttpUtil.post(apiUrl, body);
        
        JSONObject jsonResult = JSONUtil.parseObj(result);
        if (jsonResult.getInt("errcode") == 0) {
            log.setStatus("SUCCESS");
        } else {
            log.setStatus("FAILED");
            log.setErrorMessage(jsonResult.getStr("errmsg"));
        }
        log.setToUser(toUser);
        logMessage(log);
        
        // Return full response object including status and error info
        JSONObject response = new JSONObject();
        response.set("success", jsonResult.getInt("errcode") == 0);
        response.set("data", jsonResult);
        return response;
    }
}
